<?php

namespace App;

use \Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $table = 'users';

    protected $primaryKey = 'id';

    protected $fillable = ['name', 'email', 'password', 'created_at', 'updated_at', 'remember_token'];

    protected $dateFormat = 'U';

    protected $hidden = ['created_at','updated_at','password','remember_token'];

    //用户的文章
    public function posts()
    {
        return $this->hasMany('\App\Post', 'user_id', 'id');
    }

    //关注我的
    public function fans()
    {
        return $this->hasMany('\App\Fan', 'star_id', 'id');
    }


    //我关注的
    public function stars()
    {
        return $this->hasMany('\App\Fan', 'fan_id', 'id');
    }

    //关注
    public function doFan($uid)
    {
        $fan = new Fan();
        $fan->star_id = $uid;
        $this->stars()->save($fan);
    }

    //取消关注
    public function doUnFan($uid)
    {
        $fan = new Fan();
        $fan->star_id = $uid;
        $this->stars()->delete($fan);
    }

    //当前用户是否被uid关注了
    public function hasFan($uid)
    {
        return $this->fans()->where('fan_id', $uid)->count();
    }

    //当前用户是否关注了uid
    public function hasStar($uid)
    {
        return $this->stars()->where('star_id', $uid)->count();
    }

    //我收到的通知
    public function notices()
    {
        return $this->belongsToMany(\App\Notice::class, 'user_notice', 'user_id', 'notice_id')->withPivot(['user_id', 'notice_id']);
    }

    //增加通知
    public function addNotice($notice)
    {
        return $this->notices()->save($notice);
    }

    //减少通知
    public function deleteNotice($notice)
    {
        return $this->notices()->detach($notice);
    }
}
